<template>
  <a-modal
    title="添加试题"
    style="top: 20px;"
    :width="800"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item style="display:none">
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="题目类型">
        <a-select placeholder="请选择题目类型" @change="getFocus" v-decorator=" ['quType', {rules: [{required: true, message: '请选择题目类型'}]}]" allowClear>
          <a-select-option 	  v-for="(b, index) in quTypeList" :key="index" :value="b.dictValue">{{ b.dictLabel }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="请选择难易程度">
        <a-select placeholder="请选择题目类型" v-decorator="['level', {rules: [{required: true, message: '请输入选择难度'}]}]" allowClear>
          <a-select-option v-for="(b, index) in quLevelList" :key="index" :value="b.key">{{ b.value }}
          </a-select-option>
        </a-select>
        <!--              <a-input placeholder="请输入普通,较难" v-model="queryParam.level"/>-->
        <!--        <a-input placeholder="1普通,2较难" v-decorator="['level', {rules: [{required: true, message: '请输入1普通,2较难'}]}]" />-->
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="试题内容">
        <a-input placeholder="试题内容" v-decorator="['content', {rules: [{required: true, message: '请输入题目备注'}]}]" />
      </a-form-item>
      <a-radio-group  v-show="ifShow"  :default-value="1"  @change="setSelectType">
        <a-radio value="checkbox">多选题</a-radio>
        <a-radio value="radio">单选题</a-radio>
      </a-radio-group>
      <a-button v-show="isbut" type="primary" icon="plus" @click="addRow(elData)">添加</a-button>
      <a-table
        size="default"
        ref="table"
        :rowKey = "this.isKey"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: selectType,getCheckboxProps: getCheckboxProps }"
        :columns="columns"
        :dataSource="elData"
      >
        <template
          v-for="col in ['content', 'analysis']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              :value="text"
              style="margin: -5px 0"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
          </div>
        </template>
         <span slot="action" slot-scope="text, record, index">
           <a-button type="danger" icon="minus" @click="DelRow(index)">删除</a-button>
         </span>
      </a-table>
    </a-form>
  </a-modal>
</template>
<script>
import { infoQuEl, saveElQu } from '@/api/elQu'
import pick from 'lodash.pick'

export default {
  name: 'ElQuModal',
  props: {
    quTypeList: {
      type: Array,
      required: true
    }
  },
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      quLevelList: [
        {
          key: 1,
          value: '简单'
        },
        {
          key: 2,
          value: '较难'
        }
      ],
      ifShow: false,
      mark: false,
      isbut: false,
      selectType: '',
      isKey: '',
      selectedRowKeys: [],
      selectedRows: [],
      // 表头
      columns: [],
      elData: [],
      xz: '',
      row: [],
      c: []
    }
  },
  beforeCreate() {
  },
  created() {
    if (this.$route.query.account.id === undefined) {
      this.$router.push({ path: '/elRepoList' })
    }
  },
  methods: {
    getCheckboxProps (record) {
      this.row.forEach(item => {
        if (item.correct === record.correct){
          this.c.push(item)
        }
      })
      this.selectedRows = this.c
      return ({
        props: {
          defaultChecked: this.c.some(item1 => item1.id === record.id)
        }
      })
    },
    handleChange (value, key, column) {
      // 输入框改变获取值
      console.log(value)
      console.log(column)
      const newData = [...this.elData];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.elData = newData;
      }
    },
    // 提取公共表头
    sharedData (val) {
      if (val === '1' || val === '2') {
        this.columns.push({
          title: '选项',
          dataIndex: 'correct',
          key: 'correct'
        }, {
          title: '选项内容',
          dataIndex: 'content',
          key: 'content',
          scopedSlots: { customRender: 'content' }
        }, {
          title: '题目解析',
          dataIndex: 'analysis',
          key: 'analysis',
          scopedSlots: { customRender: 'analysis' }
        }, {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
        if (val === '1') {
          this.selectType = 'radio'
        } else {
          this.selectType = 'checkbox'
          this.mark = true
        }
      }
      if (val === '3') {
        this.columns.push({
          title: '是否正确答案',
          dataIndex: 'correct',
          key: 'correct'
        }, {
          title: '选项内容',
          dataIndex: 'content',
          key: 'content',
          scopedSlots: { customRender: 'content' }
        }, {
          title: '题目解析',
          dataIndex: 'analysis',
          key: 'analysis',
          scopedSlots: { customRender: 'analysis' }
        }, {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
      if (val === '4') {
        this.columns.push({
          title: '选项内容',
          dataIndex: 'content',
          key: 'content',
          scopedSlots: { customRender: 'content' }
        })
      }
      if (val === '6') {
        this.columns.push({
          title: '选项内容',
          dataIndex: 'content',
          key: 'content',
          scopedSlots: { customRender: 'content' }
        }, {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
    },
    setSelectType (e) {
      // 选择题目类型
      this.selectType = e.target.value
    },
    getFocus (val) {
      this.elData = []
      this.columns = []
      console.log(val)
      if (val === '1' || val === '2') {
        this.ifShow = true
        this.isbut = true
        this.isKey = 'correct'
        this.sharedData(val)
        for (let i = 0; i < 4; i++) {
          this.addRow(i)
        }
      }
      if (val === '3') {
        this.isbut = false
        this.ifShow = false
        this.isKey = 'correct'
        for (let i = 0; i < 2; i++) {
          const newData = {
            correct: i === 0 ? '正确' : '错误',
            key: this.elData.length
          }
          this.selectType = 'radio'
          // 对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性，拷贝到当前对象之中
          this.elData = [...this.elData, newData]
        }
        this.sharedData(val)
      }
      if (val === '4') {
        this.ifShow = false
        this.sharedData(val)
      }
      if (val === '6') {
        this.ifShow = false
        this.isbut = true
        this.columns = []
        this.sharedData(val)
      }
    },
    addRow (e) {
      // 添加表格
      const newData = {
        correct: String.fromCharCode(65 + this.elData.length),
        key: this.elData.length
      }
      // 对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性，拷贝到当前对象之中
      this.elData = [...this.elData, newData]
    },
    DelRow (key) {
      // 必须从最后删除
      if (key + 1 === this.elData.length){
        const elData = [...this.elData]
        this.elData = elData.filter(item => item.key !== key)
      } else {
        this.$message.info('请从最后开始删除')
      }
      // this.elData.pop()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    add() {
      this.form.resetFields()
      this.edit({ id: 0 })
    },
    edit(record) {
      this.elData = []
      this.columns = []
      console.log(record)
      this.isKey = 'correct'
      this.sharedData(record.quType + '')
      // 将对象拷贝，第一个是目标源，后面都是源对象
      this.mdl = Object.assign(record)
      this.visible = true
      // 查询问题选项
      infoQuEl(record.id).then(res => {
        for (let i = 0; i < res.el.length; i++) {
          if (res.el[i].isRight === 1) {
            // this.xz = res.el[i].correct
            this.row.push(res.el[i])
          }
          res.el[i].correct = String.fromCharCode(65 + i)
        }
        this.elData = res.el
      })
      // 异步更新
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'quType', 'level', 'content'))
      })
    },
    handleSubmit (e) {
      this.confirmLoading = true
      e.preventDefault()
      // 没有题库id 就返回题库页面
      if (this.$route.query.account.id === undefined) {
        this.$router.push({ path: '/elRepoList' })
      }
      // 将对象整和在一个对象中
      if (this.selectedRows.length < 1 && this.mark) {
        this.$message.info('多选题 请选择俩个以上答案')
        this.visible = false
      } else {
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
            if (values.id === 0) {
              delete values.id
            }
            values.el = this.elData
            values.row = this.selectedRows
            values.repoId = this.$route.query.account.id
            saveElQu(values).then(res => {
              if (res.code === 0) {
                this.elData = []
                this.data = []
                this.$message.success('保存成功')
                this.$emit('ok')
                this.visible = false
              } else {
                this.$message.error(res.msg)
              }
            }).catch(() => {
              this.$message.error('系统错误，请稍后再试')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        })
      }
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
